package org.binglan.youziyuepai.utils;


import okhttp3.*;

import java.io.IOException;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/4/6 17:13
 */
public class OkHttpUtils {
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private OkHttpUtils() {
    }

    private static class InstanceHolder {
        private static final OkHttpClient INSTANCE = new OkHttpClient();
    }

    public static OkHttpClient getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * Get 请求，
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
        OkHttpClient client = getInstance();

        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * post 请求
     *
     * @param url
     * @param json json 字符串
     * @return
     */
    public static String doPost(String url, String json) {
        OkHttpClient client = getInstance();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            return null;
        }

    }
}
